package com.jielin.handling.service.tsuspect.impl;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.github.pagehelper.PageHelper;
import com.jielin.handling.entity.role.Role;
import com.jielin.handling.entity.room.RoomInformation;
import com.jielin.handling.entity.suspectandcase.SuspectAndCase;
import com.jielin.handling.entity.tsuspect.*;
import com.jielin.handling.entity.virtual.Virtual;
import com.jielin.handling.entity.vo.CasePicVo;
import com.jielin.handling.entity.vo.PoliceVo;
import com.jielin.handling.entity.vo.TSuspecListVo;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.mapper.police.PoliceCaseMapper;
import com.jielin.handling.mapper.role.RoleMapper;
import com.jielin.handling.mapper.room.RoomInformationMapper;
import com.jielin.handling.mapper.tsuspect.TBraceletMapper;
import com.jielin.handling.mapper.tsuspect.TSuspecMapper;
import com.jielin.handling.mapper.tsuspect.TSuspectVirtualMapper;
import com.jielin.handling.service.material.MaterialTypeService;
import com.jielin.handling.service.tsuspect.TSuspectService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.DateUtil;
import com.jielin.handling.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenzhang
 * @date 2019/3/14 - 9:39
 */
@Service
@Slf4j
public class TSuspectServiceImpl implements TSuspectService {
    @Autowired
    TSuspecMapper tSuspecMapper;
    @Autowired
    TSuspectVirtualMapper tSuspectVirtualMapper;
    @Autowired
    TBraceletMapper TBraceletMapper;
    @Autowired
    RoomInformationMapper roomInformationMapper;
    @Autowired
    MaterialTypeService materialTypeService;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    private XskyService xskyService;
    @Autowired
    private PoliceCaseMapper policeCaseMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateSuspect(TSuspec tSuspec) {
        log.info("tSuspec:{}", JSONObject.toJSONString(tSuspec));
        String idValue = tSuspec.getIdValue();
        try {

            List<String> str = tSuspecMapper.selectSuspectByIdValue(idValue);
            if (str.size() != 0) {
                for (String id : str) {
                    tSuspecMapper.updateIsNew(id);
                }
            }
            tSuspec.setIsNew(1);
            return tSuspecMapper.updateSuspect(tSuspec);
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }

    }

    @Override
    public void deleteVitual(String id) {
        tSuspecMapper.deleteVitual(id);
    }

    @Override
    public void insertVitual(TSuspectVirtual tSuspectVirtual) {
        tSuspectVirtualMapper.insertVitual(tSuspectVirtual);
    }

    @Override
    public int creatId(String id) {
        log.info("id:{}", JSONObject.toJSONString(id));
        return tSuspecMapper.creatId(id);
    }

    @Override
    public TSuspecListVo selectState(TSuspec tsuspect) {
        log.info("tsuspect:{}", tsuspect);
        return tSuspecMapper.selectState(tsuspect);
    }

    @Override
    public List<DecicesStateVo> deviceState(String organizationId) {
        List<RoomInformation> list = roomInformationMapper.findAllRoomStatus(organizationId);// 获取所有房间的信息
        List<DecicesStateVo> truelist = new ArrayList<DecicesStateVo>();
        for (RoomInformation roomInformation : list) {
            DecicesStateVo ds = new DecicesStateVo();
            ds.setRoomName(roomInformation.getRoomname());
            List<DecicesStateVo> dsvlst = tSuspecMapper.deviceState(roomInformation.getId());
            for (int i = 0; i < dsvlst.size(); i++) {
                if (StringUtil.isEmpty(dsvlst.get(i).getEquipmentName())) {
                    ds.getEquipmentStatusMap().put("无此设备" + i, 0);
                } else {
                    ds.getEquipmentStatusMap().put(dsvlst.get(i).getEquipmentName(),
                            dsvlst.get(i).getEquipmentStatus());
                }
            }
            truelist.add(ds);
        }
        log.info("===TSuspectServiceImpl==>deviceState()==>tSuspecMapper.deviceState()获取所有房间的信息结束");

        return truelist;

    }

    @Override
    public List<TSuspec> unRelated(TSuspec suspec) {
        log.info("suspec:{}", JSONObject.toJSONString(suspec));
        List<TSuspec> list = null;
        try {
            PageHelper.startPage(suspec.getPageNum(), suspec.getPageSize());
            list = tSuspecMapper.unRelated(suspec);
            for (TSuspec tSuspec : list) {
                if (StringUtil.isEmpty(tSuspec.getHeadPhoto())) {
                    if (tSuspec.getSex() == 1) {
                        tSuspec.setHeadPhoto(ConstantUtil.returnManPhoto());
                    } else {
                        tSuspec.setHeadPhoto(ConstantUtil.returnWoManPhoto());
                    }
                } else {
                    if (!ConstantUtil.XSKYRESTORAGE) {
                        String returnPath = ConstantUtil.SERVER_URL + tSuspec.getHeadPhoto();
                        tSuspec.setHeadPhoto(returnPath);
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public int addBracelet(TBracelet tBracelet) {
        tBracelet.setId(StringUtil.generatorUUID());
        log.info("tSuspec:{}", JSONObject.toJSONString(tBracelet));
        return TBraceletMapper.insert(tBracelet);

    }

    @Override
    public List<TSuspec> selectSuspect(SuspectVo vo) {
        log.info("vo:{}", vo);
        List<TSuspec> list = null;
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        try {
            list = tSuspecMapper.selectSusceptListBySearch(vo);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;

    }

    @Override
    public int savePhoto(String path, String id) {
        log.info("path:{}", path);
        log.info("id:{}", id);
        return tSuspecMapper.savePhoto(path, id);
    }

    @Override
    public int highMeter(String path, String suspectId) {
        log.info("path:{}", path);
        log.info("id:{}", suspectId);
        String id = StringUtil.generatorUUID();
        return tSuspecMapper.highMeter(path, suspectId, id);
    }

    @Override
    public int updateRelatedCases(TSuspec suspec) {
        log.info("suspec:{}", suspec);
        try {
            // 创建电子卷宗与卷宗记录
///			materialTypeService.findMeaterialmodel(suspec.getCaseCode(), suspec.getCaseName(), suspec.getPoliceId(), suspec.getId());
            new Thread(
                    new ExecuteThread(suspec.getCaseCode(), suspec.getCaseName(), suspec.getPoliceId(), suspec.getId()))
                    .start();
            return tSuspecMapper.updateRelatedCases(suspec);
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
    }

    public class ExecuteThread implements Runnable {// 创建电子卷宗
        String caseCode;
        String caseName;
        String policeId;
        String suspectId;

        public ExecuteThread(String caseCode, String caseName, String policeId, String suspectId) {
            this.caseCode = caseCode;
            this.caseName = caseName;
            this.policeId = policeId;
            this.suspectId = suspectId;
        }

        @Override
        public void run() {
            // 新增卷宗操作
            if (ConstantUtil.XSKYRESTORAGE) {
                materialTypeService.findMeaterialmodel2(caseCode, caseName, policeId, suspectId, 0);
            } else {
                materialTypeService.findMeaterialmodel(caseCode, caseName, policeId, suspectId, 0);
            }
        }
    }

    @Override
    public TSuspec selectStatue(String id) {
        log.info("id:{}", id);
        return tSuspecMapper.selectStatue(id);
    }

    @Override
    public List<TSuspec> auditFailed(TSuspec suspec) {
        log.info("suspec:{}", JSONObject.toJSONString(suspec));
        List<TSuspec> list = null;
        try {
            PageHelper.startPage(suspec.getPageNum(), suspec.getPageSize());
            list = tSuspecMapper.auditFailed(suspec);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;

    }

    @Override
    public List handlingState(int pageNum, int pageSize) {
        List list = null;
        try {
            PageHelper.startPage(pageNum, pageSize);
            list = tSuspecMapper.handlingState();
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public List countCase(TSuspec tsuspect) {
        log.info("tsuspect:{}", JSONObject.toJSONString(tsuspect));
        List<TSuspec> list = null;
        try {
            PageHelper.startPage(tsuspect.getPageNum(), tsuspect.getPageSize());
            list = tSuspecMapper.countCase(tsuspect);
            for (TSuspec tSuspec : list) {
                if (!StringUtil.isEmpty(tSuspec.getCrimeTime())) {
                    String number = tSuspec.getCrimeTime();
                    String startDate = number.substring(0, number.indexOf("-"));
                    String endDate = number.substring(number.indexOf("-") + 1);
                    Date dd = DateUtil.getDateByBaseStr(startDate, DateUtil.LOCATE_DATE_FORMAT);
                    String editStartDate = DateUtil.formatDate(dd, DateUtil.DATE_FORMAT_MINUS);

                    Date dd1 = DateUtil.getDateByBaseStr(endDate, DateUtil.LOCATE_DATE_FORMAT);
                    String editEndDate = DateUtil.formatDate(dd1, DateUtil.DATE_FORMAT_MINUS);
                    // String editEndDate=DateUtil.stampToDate(endDate);
                    tSuspec.setCrimeTime(editStartDate + "——" + editEndDate);
                }
            }
            for (TSuspec tSuspec : list) {

            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public Map<String, List<Object>> casePic(String policeId) {
        log.info("suspectId:{}", JSONObject.toJSONString(policeId));
        Map<String, List<Object>> map = new HashMap<>();
        List<Object> title = new ArrayList<>();// 卷宗材料出入柜统计分析
        title.add("刑事案件总数");
        title.add("民事案件总数");
        title.add("行政案件总数");
        title.add("总数");
        List<Object> value = new ArrayList<>();// 卷宗材料出入柜状态数据
        Integer criminalCase = 0;
        Integer civilCase = 0;
        Integer politicsCase = 0;
        CasePicVo vo = tSuspecMapper.casePic(policeId);
        if (vo != null) {
            value.add(vo.getCriminalCase());
            value.add(vo.getCivilCase());
            value.add(vo.getPoliticsCase());
            value.add(vo.getCriminalCase() + vo.getCivilCase() + vo.getPoliticsCase());
        }
        map.put("title", title);
        map.put("value", value);
        return map;
    }

    @Override
    public List<String> selectNameByCase(String caseCode) {
        log.info("caseCode:{}", JSONObject.toJSONString(caseCode));
        return tSuspecMapper.selectNameByCase(caseCode);
    }

    @Override
    public PoliceVo selectPolice(String id) {
        log.info("id:{}", id);
        PoliceVo policeVo = tSuspecMapper.selectPolice(id);
        if (policeVo != null) {
            if (StringUtil.isEmpty(policeVo.getHeadPhoto())) {
                if (policeVo.getSex() == 1) {
                    policeVo.setHeadPhoto(ConstantUtil.returnPoliceManPhoto());
                } else {
                    policeVo.setHeadPhoto(ConstantUtil.returnPoliceWoManPhoto());
                }
            } else {
                if (!ConstantUtil.XSKYRESTORAGE) {
                    String returnPath = ConstantUtil.SERVER_URL + policeVo.getHeadPhoto();
                    policeVo.setHeadPhoto(returnPath);
                }
            }
            policeVo.setRoleName(roleMapper.findRoleByPoliceId(id).stream()
                    .map(Role::getRoleName).collect(Collectors.joining(ConstantUtil.COMMA_SEPARATOR)));
        }
        return policeVo;
    }

    @Override
    public List<PoliceVo> selectRecorder(String policeId) {
        log.info("policeId:{}", policeId);
        return tSuspecMapper.selectRecorder(policeId);
    }

    @Override
    public Map handNumber(String handleUnitCode) {
        log.info("handleUnitCode:{}", handleUnitCode);
        Integer suspectNumber = tSuspecMapper.handSusNumber(handleUnitCode);// 获得嫌疑人人数

        Integer policeNumber = tSuspecMapper.handPoNumber(handleUnitCode);// 获得民警人数
        Map map = new HashMap();
        map.put("suspectNumber", suspectNumber);
        map.put("policeNumber", policeNumber);
        return map;
    }

    @Override
    public TSuspec selectById(String id) {
        TSuspec tSuspec = tSuspecMapper.selectById(id);
        if (tSuspec != null) {
            if (StringUtil.isEmpty(tSuspec.getHeadPhoto())) {
                if (tSuspec.getSex() == 1) {
                    tSuspec.setHeadPhoto(ConstantUtil.returnManPhoto());
                } else {
                    tSuspec.setHeadPhoto(ConstantUtil.returnWoManPhoto());
                }
            } else {
                if (!ConstantUtil.XSKYRESTORAGE) {
                    String returnPath = ConstantUtil.SERVER_URL + tSuspec.getHeadPhoto();
                    tSuspec.setHeadPhoto(returnPath);
                }

            }
        }
        return tSuspec;

    }

    @Override
    public List<TSuspec> selectByStatus(TSuspec suspec) {
        log.info("suspec:{}", suspec);
        List<TSuspec> lists = tSuspecMapper.selectByStatus(suspec);
        for (TSuspec tSuspec : lists) {
            if (tSuspec != null) {
                if (StringUtil.isEmpty(tSuspec.getHeadPhoto())) {
                    if (tSuspec.getSex() == 1) {
                        tSuspec.setHeadPhoto(ConstantUtil.returnManPhoto());
                    } else {
                        tSuspec.setHeadPhoto(ConstantUtil.returnWoManPhoto());
                    }
                } else {
                    if (!ConstantUtil.XSKYRESTORAGE) {
                        String returnPath = ConstantUtil.SERVER_URL + tSuspec.getHeadPhoto();
                        tSuspec.setHeadPhoto(returnPath);
                    }
                }
            }
            log.info("======>" + tSuspec.toString());
        }
        return lists;
    }

    @Override
    public Map selectByCaseCode(TSuspec tSuspec) {
        log.info("tSuspec:{}", tSuspec);
        List<TSuspec> suspect = tSuspecMapper.selectByCaseCode(tSuspec);
        for (TSuspec sus : suspect) {
            if (StringUtil.isEmpty(sus.getHeadPhoto())) {
                if (sus.getSex() == 1) {
                    sus.setHeadPhoto(ConstantUtil.returnManPhoto());
                } else {
                    sus.setHeadPhoto(ConstantUtil.returnWoManPhoto());
                }
            } else {
                if (!ConstantUtil.XSKYRESTORAGE) {
                    String returnPath = ConstantUtil.SERVER_URL + sus.getHeadPhoto();
                    sus.setHeadPhoto(returnPath);
                }

            }
        }
        List<TSuspec> tSuspecs = tSuspecMapper.unSelectByCaseCode(tSuspec);
        for (TSuspec sus1 : tSuspecs) {
            if (StringUtil.isEmpty(sus1.getHeadPhoto())) {
                if (sus1.getSex() == 1) {
                    sus1.setHeadPhoto(ConstantUtil.returnManPhoto());
                } else {
                    sus1.setHeadPhoto(ConstantUtil.returnWoManPhoto());
                }
            } else {
                if (!ConstantUtil.XSKYRESTORAGE) {
                    String returnPath = ConstantUtil.SERVER_URL + sus1.getHeadPhoto();
                    sus1.setHeadPhoto(returnPath);
                }
            }
        }
        Map map = new HashMap();
        map.put("suspect", suspect);// 和民警案件关联的嫌疑人
        map.put("tSuspecs", tSuspecs);// 和民警案件不关联的嫌疑人
        return map;
    }

    @Override
    public int updateFiled(TSuspec tSuspec) {
        log.info("tSuspec:{}", JSONObject.toJSONString(tSuspec));
        return tSuspecMapper.updateFiled(tSuspec);
    }

    @Override
    public List<TSuspec> selectCodeAndName(String unitCode, String name) {
        log.info("policeId:{}", JSONObject.toJSONString(unitCode));
        return tSuspecMapper.selectCodeAndName(unitCode, name);
    }


    @Override
    public List<TSuspec> selectCompleteCase(String unitCode, String name) {
        return tSuspecMapper.selectCompleteCase(unitCode, name);
    }

    @Override
    public List<TSuspec> selectAllCodeAndName(String unitCode) {
        log.info("policeId:{}", JSONObject.toJSONString(unitCode));
        return tSuspecMapper.selectAllCodeAndName(unitCode);
    }

    @Override
    public List<TSuspec> selectPoliceByUnitcode(String unitCode) {
        log.info("unitCode:{}", JSONObject.toJSONString(unitCode));
        return tSuspecMapper.selectPoliceByUnitcode(unitCode);
    }

    @Override
    public List<TSuspec> relatedSuspect(String caseCode) {
        log.info("caseCode:{}", JSONObject.toJSONString(caseCode));
        return tSuspecMapper.relatedSuspect(caseCode);
    }

    @Override
    public List<TSuspec> selectSuspectByCaseCode(String caseCode) {
        log.info("caseCode:{}", JSONObject.toJSONString(caseCode));
        return tSuspecMapper.selectSuspectByCaseCode(caseCode);
    }

    @Override
    public List<Virtual> selectVirtual(String virtualId) {
        log.info("virtualId:{}", JSONObject.toJSONString(virtualId));
        return tSuspecMapper.selectVirtual(virtualId);
    }

    @Override
    public List<PoliceVo> selectOnlyPolice(String unitCode) {
        log.info("unitCode:{}", JSONObject.toJSONString(unitCode));
        return tSuspecMapper.selectOnlyPolice(unitCode);
    }

    @Override
    public int getCaseNumByPoliceId(TSuspec tSuspec) {
        return tSuspecMapper.getCaseNumByPoliceId(tSuspec);
    }

    @Override
    public List<TSuspec> selectSuspectnameByCaseCode(String caseCode) {
        return tSuspecMapper.selectSuspectnameByCaseCode(caseCode);
    }

    @Override
    public List<TSuspec> selectSuspectnameByUnitcode(String unitCode) {
        return tSuspecMapper.selectSuspectnameByUnitcode(unitCode);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int addSuspect(SuspectAndCase suspectAndCase) {
        try {
            int count = tSuspecMapper.selectFrequencyOfEnquiry(suspectAndCase.getIdValue(), suspectAndCase.getHandleUnitCode());//查询嫌疑人已有的审讯次数
            int mount = count > 0 ? count + 1 : 1;
            suspectAndCase.setFrequencyOfEnquiry(mount);
            return tSuspecMapper.addSuspect(suspectAndCase);
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
    }

    @Override
    public int selectByCaseCodeAndIdValue(SuspectAndCase suspectAndCase) {
        return tSuspecMapper.selectByCaseCodeAndIdValue(suspectAndCase);
    }

    @Override
    public int updateSuspect2(SuspectAndCase suspectAndCase) {
        return tSuspecMapper.updateSuspect2(suspectAndCase);
    }

    @Override
    public SuspectAndCase selectSuspectById(String id) {
        SuspectAndCase suspectAndCase = tSuspecMapper.selectSuspectById(id);
        return suspectAndCase;
    }

    @Override
    public List<TSuspec> selectSuspectNameByHandleUnitCode(String unitCode) {
        return tSuspecMapper.selectSuspectNameByHandleUnitCode(unitCode);
    }

    @Override
    public int savePhoto2(MultipartFile file, String id, String fileString) {
        log.info("id:{}", JSONObject.toJSONString(id));
        boolean isHaveFile = file != null && file.getSize() > 0;
        // 表单上传文件或base64格式
        if (isHaveFile || !StringUtil.isEmpty(fileString)) {
            String path = ConstantUtil.PHOTO_PATH + "suspect" + File.separator + "headpic" + File.separator;
            // 文件原名称
            String trueFileName = String.valueOf(System.currentTimeMillis());
            byte[] bytes = null;
            //设置Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            if (isHaveFile) {
                try {
                    String fileName = file.getOriginalFilename();
                    String fileType = fileName.substring(fileName.lastIndexOf("."));
                    String filesPath = path + trueFileName + fileType;
                    filesPath = filesPath.replace("\\", "/");
                    bytes = file.getBytes();
                    metadata.setContentType(file.getContentType());
                    xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, filesPath, bytes, metadata);
                    if (tSuspecMapper.savePhoto(ConstantUtil.XSKY_PHOTO_URL + filesPath, id) > 0) {
                        log.info("上传成功");
                    } else {
                        log.error("上传失败");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("xsky上传失败");
                }
            } else {
                try {
                    String fileType = ".png";
                    String filesPath = path + trueFileName + fileType;
                    filesPath = filesPath.replace("\\", "/");
                    BASE64Decoder decoder = new BASE64Decoder();
                    String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
                    log.info("Base64解码后:\n" + base64String);
//                    byte[] b = new byte[0];
                    bytes = decoder.decodeBuffer(base64String);
                    for (int i = 0; i < bytes.length; ++i) {
                        if (bytes[i] < 0) {// 调整异常数据
                            bytes[i] += 256;
                        }
                    }
                    try {
                        metadata.setContentType(ContentType.IMAGE_JPEG.getMimeType());
                        xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, filesPath, bytes, metadata);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("xsky上传失败！");
                    }
                    if (tSuspecMapper.savePhoto(ConstantUtil.XSKY_PHOTO_URL + filesPath, id) > 0) {
                        log.info("上传成功");
                    } else {
                        log.error("上传失败");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultEnum.FAIL.getCode();
                }
            }

            return ResultEnum.SUCCESS.getCode();
        }
        return ResultEnum.FAIL.getCode();
    }

    @Override
    public void updateIsTwotrial(String id,String caseCode) {
        tSuspecMapper.updateIsTwotrial(id);
        policeCaseMapper.updateCaseStausBycode(caseCode);
    }
}
